<template>
  <div class="favorite-posts">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>我的收藏</h1>
        <p>管理您的收藏</p>
      </div>
      <!-- Tab切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="favorite-tabs">
        <el-tab-pane label="帖子收藏" name="posts">
          <!-- 收藏帖子列表 -->
          <div class="posts-section">
            <el-card v-if="loading" class="loading-card">
              <div class="loading-content">
                <i class="el-icon-loading"></i>
                <span>加载中...</span>
              </div>
            </el-card>
            <div v-else-if="favoritePosts.length === 0" class="empty-state">
              <i class="el-icon-star-off"></i>
              <p>{{ searchKeyword || selectedCategory ? '没有找到匹配的收藏帖子' : '您还没有收藏任何帖子' }}</p>
              <el-button type="primary" @click="goToForum">去论坛逛逛</el-button>
            </div>
            <div v-else class="posts-list">
              <el-card v-for="post in favoritePosts" :key="post.id" class="post-card"
                :class="{ 'selected': selectedPosts.includes(post.id) }">
                <div class="post-header">
                  <div class="post-actions">
                    <el-button type="text" icon="el-icon-view" @click="viewPost(post.forumId)" size="small">
                      查看
                    </el-button>
                    <el-button type="text" icon="el-icon-star-on" @click="removeFavorite(post)" size="small"
                      style="color: #f56c6c;">
                      取消收藏
                    </el-button>
                  </div>
                </div>

                <h3 class="post-title" @click="viewPost(post.id)">{{ post.title }}</h3>
                <p class="post-summary">{{ post.summary }}</p>

                <div class="post-author">
                  <el-avatar :size="24" :src="post.avatar">
                    {{ (post.name || post.userName || '').charAt(0) }}
                  </el-avatar>
                  <span class="author-name">{{ post.name || post.userName || '未知用户' }}</span>
                </div>
                <div class="post-time">
                  <span>创建时间 {{ post.createTime }}</span>
                  <span>更新时间 {{ post.updateTime }}</span>
                </div>
              </el-card>
            </div>
            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
                :total="totalPostCount" layout="prev, pager, next, jumper, total">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="宠物收藏" name="pets">
          <!-- 收藏宠物列表 -->
          <div class="pets-section">
            <el-card v-if="loading" class="loading-card">
              <div class="loading-content">
                <i class="el-icon-loading"></i>
                <span>加载中...</span>
              </div>
            </el-card>

            <div v-else-if="favoritePets.length === 0" class="empty-state">
              <i class="el-icon-star-off"></i>
              <p>{{ petSearchKeyword || selectedPetType ? '没有找到匹配的收藏宠物' : '您还没有收藏任何宠物' }}</p>
              <el-button type="primary" @click="goToAdoption">去领养页面看看</el-button>
            </div>
            <div v-else class="posts-list">

              <el-card v-for="pet in favoritePets" :key="pet.id" class="post-card"
                :class="{ 'selected': selectedPets.includes(pet.id) }">
                <div class="post-header">
                  <div class="post-actions">
                    <el-button type="text" icon="el-icon-view" @click="viewPetDetail(pet.petId)" size="small">
                      查看详情
                    </el-button>
                    <el-button type="text" icon="el-icon-star-on" @click="removePetFavorite(pet)" size="small"
                      style="color: #f56c6c;">
                      取消收藏
                    </el-button>
                  </div>
                </div>
                <div class="post-content">
                  <div class="pet-image-small">
                    <img :src="pet.image" :alt="pet.name" />
                  </div>
                  <h3 class="post-title">{{ pet.name }}</h3>
                </div>
                <div class="post-time">
                  <span>创建时间 {{ pet.createTime }}</span>
                  <span>更新时间 {{ pet.updateTime }}</span>
                </div>
              </el-card>
            </div>
            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination @current-change="handlePetPageChange" :current-page="petCurrentPage" :page-size="pageSize"
                :total="totalPetCount" layout="prev, pager, next, jumper, total">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { getPetRescueList, deletePetRescueBatch } from '@/api/pet-collection'
import { getForumCollectionList, deleteForumCollectionBatch } from '@/api/forum-collection'
export default {
  name: 'FavoritePosts',
  data() {
    return {
      // Tab切换
      activeTab: 'posts',

      // 帖子相关数据
      loading: true,
      searchKeyword: '',
      selectedCategory: '',
      sortBy: 'favoriteTime',
      currentPage: 1,
      pageSize: 10,
      selectedPosts: [],
      favoritePosts: [],
      totalPetCount: 0,
      totalPostCount: 0,
      // 宠物相关数据
      petSearchKeyword: '',
      selectedPetType: '',
      petSortBy: 'favoriteTime',
      petCurrentPage: 1,
      selectedPets: [],
      favoritePets: []
    }
  },
  methods: {
    // Tab切换
    handleTabClick(tab) {
      this.activeTab = tab.name
      if (tab.name === 'posts' && this.favoritePosts.length === 0) {
        this.loadFavoritePosts()
      } else if (tab.name === 'pets' && this.favoritePets.length === 0) {
        this.loadFavoritePets()
      }
    },

    async loadFavoritePosts() {
      this.loading = true
      try {
        // 这里应该调用API获取用户收藏的帖子
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        const response = await getForumCollectionList(params)
        this.favoritePosts = response.data.rows || []
        this.totalPostCount = response.data.total || 0
      } catch (error) {
        this.$message.error('加载收藏帖子失败')
      } finally {
        this.loading = false
      }
    },

    async loadFavoritePets() {
      this.loading = true
      try {
        // 这里应该调用API获取用户收藏的宠物
        const params = {
          pageNum: this.petCurrentPage,
          pageSize: this.pageSize
        }
        const response = await getPetRescueList(params)
        this.favoritePets = response.data.rows || []
        this.totalPetCount = response.data.total || 0
      } catch (error) {
        this.$message.error('加载收藏宠物失败')
      } finally {
        this.loading = false
      }
    },

    filterPosts() {
      this.currentPage = 1
      this.selectedPosts = []
    },

    filterPets() {
      this.petCurrentPage = 1
      this.selectedPets = []
    },

    sortPosts() {
      this.currentPage = 1
      this.selectedPosts = []
    },

    sortPets() {
      this.petCurrentPage = 1
      this.selectedPets = []
    },

    handlePageChange(page) {
      this.currentPage = page
      this.selectedPosts = []
    },

    handlePetPageChange(page) {
      this.petCurrentPage = page
      this.selectedPets = []
    },

    handleSelectionChange() {
      // 选择状态变化时的处理
    },

    handlePetSelectionChange() {
      // 宠物选择状态变化时的处理
    },

    clearSelection() {
      this.selectedPosts = []
    },

    clearPetSelection() {
      this.selectedPets = []
    },

    viewPost(postId) {
      this.$router.push(`/forum/post/${postId}`)
    },

    async removeFavorite(post) {
      try {
        await this.$confirm(`确定要取消收藏"${post.title}"吗？`, '确认取消收藏', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await deleteForumCollectionBatch(post.id)
        if (res.code === 200) {
          const index = this.favoritePosts.findIndex(p => p.id === post.id)
          if (index > -1) {
            this.favoritePosts.splice(index, 1)
            this.$message.success('已取消收藏')
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消收藏失败')
        }
      }
    },

    async removePetFavorite(pet) {
      try {
        await this.$confirm(`确定要取消收藏"${pet.name}"吗？`, '确认取消收藏', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const res = await deletePetRescueBatch(pet.id)
        if (res.code === 200) {
          const index = this.favoritePets.findIndex(p => p.id === pet.id)
          if (index > -1) {
            this.favoritePets.splice(index, 1)
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消收藏失败')
          console.error('取消收藏失败:', error)
        }
      }
    },
    goToForum() {
      this.$router.push('/forum')
    },

    goToAdoption() {
      this.$router.push('/adoption-browse')
    },

    viewPetDetail(petId) {
      this.$router.push(`/pet-detail/${petId}`)
    },
  },

  mounted() {
    this.loadFavoritePosts()
    this.loadFavoritePets()
  }
}
</script>

<style scoped>
.favorite-posts {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}



.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.posts-section {
  margin-top: 20px;
}

.loading-card {
  text-align: center;
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-state i {
  font-size: 64px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.batch-selection-info {
  margin-bottom: 16px;
}

.post-card {
  transition: all 0.3s ease;
  position: relative;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.post-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.post-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 12px;
}

.post-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.post-category .el-tag {
  margin-right: 8px;
}

.post-actions {
  display: flex;
  gap: 8px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.4;
  cursor: pointer;
  transition: color 0.3s ease;
}

.post-title:hover {
  color: #409eff;
}

.post-summary {
  color: #7f8c8d;
  line-height: 1.6;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-author {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
}

.author-name {
  color: #606266;
  font-weight: 500;
}

.author-level {
  color: #909399;
  font-size: 12px;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-item i {
  font-size: 14px;
}

.post-time {
  color: #c0c4cc;
  display: flex;
  justify-content: flex-end;
  gap: 20px;
}

.publish-time {
  font-size: 12px;
  color: #d3d4d6;
}

.post-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pet-image-small {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.pet-image-small img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>